package com.sskj.uboex.presenter;

import com.google.gson.Gson;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.DisposUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.uboex.bean.AppVersionBean;
import com.sskj.uboex.bean.SocketSendBean;
import com.sskj.uboex.http.HttpConfig;
import com.sskj.uboex.ui.activity.MainActivity;

import io.reactivex.disposables.Disposable;


public class MainActivityPresenter extends BasePresenter<MainActivity> {
    private WebSocketObserver stockSocket;
    private Disposable stockDisposable;
    private WebSocketObserver stockSocketFive;
    private Disposable stockDisposableFive;

    public void initWebSocket() {
        if (stockSocket == null) {
            stockSocket = httpService.pushCoinType(Constans.NO_FIVE_PUSH);
            stockDisposable = stockSocket
                    .map(s -> new Gson().fromJson(s, StockCoinBean.StockProductVOBean.class))
                    .subscribe(data -> RxBus.getDefault().post(data), e -> {
                    });
            stockSocketFive = httpService.pushCoinFive(Constans.FIVE_PUSH);
            stockDisposableFive = stockSocketFive
                    .map(s -> new Gson().fromJson(s, WSFiveBean.class))
                    .subscribe(data -> RxBus.getDefault().post(data), e -> {
                    });
        } else {
            stockSocket.send(new Gson().toJson(new SocketSendBean(Constans.NO_FIVE_PUSH)));
            stockSocketFive.send(new Gson().toJson(new SocketSendBean(Constans.FIVE_PUSH)));
        }

    }

    public void closeWebSocket() {
        stockSocket = null;
        stockSocketFive = null;
        DisposUtil.close(stockDisposable);
        DisposUtil.close(stockDisposableFive);
    }

    public void getNewVersion() {
        httpService.getVersion()
                .tag(this)
                .execute(new JsonCallBack<HttpData<AppVersionBean>>() {
                    @Override
                    public void onSuccess(Response<HttpData<AppVersionBean>> response) {
                        HttpData<AppVersionBean> httpData = response.body();
                        if (httpData.getStatus() == HttpConfig.OK) {
                            mView.onVersionDataSuccess(httpData.getData());
                        }
                    }
                });
    }


}
